package com.repair.system.service;

import com.repair.system.entity.FaultRecord;
import com.repair.system.repository.FaultRecordRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class FaultRecordService {
    private final FaultRecordRepository faultRecordRepository;
    
    public List<FaultRecord> getAllFaults() {
        return faultRecordRepository.findAll();
    }
    
    public FaultRecord getFaultById(Long id) {
        return faultRecordRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("故障记录不存在"));
    }
    
    public FaultRecord saveFault(FaultRecord fault) {
        if (fault.getFaultNumber() == null || fault.getFaultNumber().isEmpty()) {
            fault.setFaultNumber(generateFaultNumber());
        }
        return faultRecordRepository.save(fault);
    }
    
    public List<FaultRecord> getRecentFaults() {
        return faultRecordRepository.findTop10ByOrderByCreatedAtDesc();
    }
    
    public long getPendingFaultCount() {
        return faultRecordRepository.countByStatus(FaultRecord.FaultStatus.PENDING);
    }
    
    public long getResolvedFaultCount() {
        return faultRecordRepository.countByStatus(FaultRecord.FaultStatus.RESOLVED);
    }
    
    private String generateFaultNumber() {
        return "F" + LocalDateTime.now().getYear() + 
               String.format("%06d", faultRecordRepository.count() + 1);
    }
}
